package com.code.qgjx.controller.dealcontroller;

import com.alibaba.fastjson.JSON;
import com.code.qgjx.entity.WorkPush;
import com.code.qgjx.service.WorkPushService;
import com.code.qgjx.mapper.WorkPushMapper;
import com.code.qgjx.tools.Layui;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/Sys")
@Api("工作量上报管理相关api")
@Slf4j
public class WorkPushController {

    @Autowired
    private WorkPushService workPushService;

    @Autowired
    private WorkPushMapper workPushMapper;

    /**
     * 根据ID获取工作量上报记录
     * @param id 工作量上报记录的ID
     * @return 包含工作量上报记录的Map对象
     */
    @RequestMapping("/getWorkPush")
    @ResponseBody
    public Map<String, Object> getWorkPush(@RequestParam("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> workPush = workPushService.getWorkPush(id);
        if (workPush != null) {
            result.put("code", 0);
            result.put("data", workPush);
        } else {
            result.put("code", 1);
            result.put("msg", "未找到对应的工作量上报记录");
        }
        return result;
    }

    /**
     * 获取工作量上报记录列表
     * @param limit 每页记录数
     * @param page 页码
     * @param userId 用户ID（可选）
     * @param status 状态（可选）
     * @return 包含工作量上报记录列表的JSON字符串
     */
    @RequestMapping("/getWorkPushList")
    @ResponseBody
    public String getWorkPushList(@RequestParam("limit") String limit, @RequestParam("page") String page,
                                 @RequestParam(value = "userId", required = false) String userId,
                                  @RequestParam(value = "status", required = false) String status) {
        int lim = Integer.parseInt(limit);
        int start = (Integer.parseInt(page) - 1) * lim;
        List<Map<String, Object>> workPushes = workPushService.getAllWorkPushWithPage(start, lim, userId,status);
        int total = workPushService.getWorkPushCount(userId);
        return JSON.toJSONString(Layui.data(total, workPushes));
    }

    /**
     * 添加新的工作量上报记录
     * @param map 包含工作量上报信息的Map对象
     * @return 添加结果的字符串表示
     */
    @RequestMapping("/addWorkPush")
    @ResponseBody
    public String addWorkPush(@RequestBody Map<String, Object> map) {
        // 验证工作时长
        int workingHours = Integer.parseInt(map.get("workingHours").toString());
        if (workingHours <= 0 || workingHours > 50) {
            return "invalid_hours";  // 返回特殊状态，表示工作时长无效
        }

        // 检查同月是否已有记录
        String year = map.get("year").toString();
        String month = map.get("month").toString();
        String userId = map.get("userId").toString();

        Map<String, Object> existingWorkPush = workPushMapper.checkExistingInMonth(year, month, userId, null);
        if (existingWorkPush != null) {
            return "duplicate_month";  // 返回特殊状态，表示当月已有记录
        }

        WorkPush workPush = new WorkPush();
        workPush.setYear(year);
        workPush.setSemester(map.get("semester").toString());
        workPush.setMonth(month);
        workPush.setDepartmentName(map.get("departmentName").toString());
        workPush.setTeacher(map.get("teacher").toString());
        workPush.setWorkingHours(workingHours);
        workPush.setTimeSlot(map.get("timeSlot").toString());
        workPush.setUserId(userId);
        workPush.setJobPositionId(Long.parseLong(map.get("jobPositionId").toString()));
        workPush.setState(0);  // 设置初始状态为未审批

        return workPushService.createWorkPush(workPush) ? "success" : "failure";
    }

    /**
     * 删除指定ID的工作量上报记录
     * @param id 工作量上报记录的ID
     * @return 删除结果的字符串表示
     */
    @RequestMapping("/deleteWorkPush")
    @ResponseBody
    public String deleteWorkPush(@RequestParam("id") Long id) {
        return workPushService.deleteWorkPush(id) ? "success" : "failure";
    }

    /**
     * 批量删除工作量上报记录
     * @param nums 包含多个ID的字符串，用逗号分隔
     * @return 删除结果的字符串表示
     */
    @RequestMapping("/deleteWorkPushes")
    @ResponseBody
    public String deleteWorkPushes(@RequestParam("nums") String nums) {
        String[] ids = nums.split(",");
        boolean success = true;

        for (String id : ids) {
            if (!id.isEmpty()) {
                success &= workPushService.deleteWorkPush(Long.parseLong(id));
            }
        }

        return success ? "success" : "failure";
    }

    /**
     * 更新工作量上报记录
     * @param map 包含更新后工作量上报信息的Map对象
     * @return 更新结果的字符串表示
     */
    @RequestMapping("/updateWorkPush")
    @ResponseBody
    public String updateWorkPush(@RequestBody Map<String, Object> map) {
        // 先获取原有记录，保留state和remark字段
        Long id = Long.parseLong(map.get("id").toString());
        Map<String, Object> originalWorkPush = workPushService.getWorkPush(id);
        if (originalWorkPush == null) {
            return "failure";
        }

        // 检查审批状态，如果已审批通过则不允许修改
        Integer state = (Integer) originalWorkPush.get("state");
        if (state != null && state == 1) {
            return "approved";  // 返回特殊状态，表示已审批通过不能修改
        }

        // 验证工作时长
        int workingHours = Integer.parseInt(map.get("workingHours").toString());
        if (workingHours <= 0 || workingHours > 50) {
            return "invalid_hours";  // 返回特殊状态，表示工作时长无效
        }

        // 检查同月是否已有其他记录
        String year = map.get("year").toString();
        String month = map.get("month").toString();
        String userId = map.get("userId").toString();

        Map<String, Object> existingWorkPush = workPushMapper.checkExistingInMonth(year, month, userId, id);
        if (existingWorkPush != null) {
            return "duplicate_month";  // 返回特殊状态，表示当月已有记录
        }

        WorkPush workPush = new WorkPush();
        workPush.setId(id);
        workPush.setYear(map.get("year").toString());
        workPush.setSemester(map.get("semester").toString());
        workPush.setMonth(map.get("month").toString());
        workPush.setDepartmentName(map.get("departmentName").toString());
        workPush.setTeacher(map.get("teacher").toString());
        workPush.setWorkingHours(workingHours);
        workPush.setTimeSlot(map.get("timeSlot").toString());
        workPush.setUserId(map.get("userId").toString());
        workPush.setJobPositionId(Long.parseLong(map.get("jobPositionId").toString()));
        // 保持原有的审批状态和备注
        workPush.setState((Integer) originalWorkPush.get("state"));
        workPush.setRemark((String) originalWorkPush.get("remark"));

        return workPushService.updateWorkPush(workPush) ? "success" : "failure";
    }

    /**
     * 审批工作量上报记录
     * @param map 包含审批信息的Map对象
     * @return 审批结果的字符串表示
     */
    @RequestMapping("/approveWorkPush")
    @ResponseBody
    public String approveWorkPush(@RequestBody Map<String, Object> map) {
        Long id = Long.parseLong(map.get("id").toString());
        Integer state = Integer.parseInt(map.get("state").toString());
        String remark = map.get("remark") != null ? map.get("remark").toString() : null;

        return workPushService.approveWorkPush(id, state, remark) ? "success" : "failure";
    }

    /**
     * 搜索工作量上报记录
     * @param params 包含搜索条件的Map对象
     * @return 包含搜索结果的JSON字符串
     */
    @RequestMapping("/searchWorkPush")
    @ResponseBody
    public String searchWorkPush(@RequestParam Map<String, Object> params) {
        int limit = Integer.parseInt(params.getOrDefault("limit", "10").toString());
        int page = Integer.parseInt(params.getOrDefault("page", "1").toString());
        int start = (page - 1) * limit;
        String userId = null;
        if (params.get("userId") != null){
            userId = params.get("userId").toString();
        }

        // 构建查询条件
        WorkPush searchWorkPush = new WorkPush();
        if (params.get("year") != null && !params.get("year").toString().trim().isEmpty()) {
            searchWorkPush.setYear(params.get("year").toString());
        }
        if (params.get("semester") != null && !params.get("semester").toString().trim().isEmpty()) {
            searchWorkPush.setSemester(params.get("semester").toString());
        }
        if (params.get("month") != null && !params.get("month").toString().trim().isEmpty()) {
            searchWorkPush.setMonth(params.get("month").toString());
        }
        if (params.get("departmentName") != null && !params.get("departmentName").toString().trim().isEmpty()) {
            searchWorkPush.setDepartmentName(params.get("departmentName").toString());
        }
        if (params.get("teacher") != null && !params.get("teacher").toString().trim().isEmpty()) {
            searchWorkPush.setTeacher(params.get("teacher").toString());
        }
        if (params.get("workingHours") != null && !params.get("workingHours").toString().trim().isEmpty()) {
            searchWorkPush.setWorkingHours(Integer.parseInt(params.get("workingHours").toString()));
        }
        if (params.get("state") != null && !params.get("state").toString().trim().isEmpty()) {
            searchWorkPush.setState(Integer.parseInt(params.get("state").toString()));
        }
        searchWorkPush.setUserId(userId);

        List<Map<String, Object>> workPushes = workPushService.searchWorkPush(searchWorkPush, start, limit);
        int total = workPushService.getSearchWorkPushCount(searchWorkPush);

        return JSON.toJSONString(Layui.data(total, workPushes));
    }
}
